package com.qf.controller;

import com.qf.service.AuthService;
import com.qf.util.CookieUtil;
import com.qf.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 授权
 * @author 千锋健哥
 */
@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private AuthService authService;

    @RequestMapping("/login")
    public String login(String userName, String password, HttpServletResponse response) {
        //1. 判断用户名密码不为空
        if (StringUtils.isEmpty(userName)) {
            return "用户名为空!";
        }
        if (StringUtils.isEmpty(password)) {
            return "密码为空!";
        }

        //2. 调用service校验
        boolean flag = authService.login(userName, password);
        if (flag) {
            //3. 生成jwt返回, 并且将jwt写入到浏览器cookie中
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), userName, null);
            CookieUtil.addCookie(response, "localhost", "/", "token", token, -1, false);
            return token;
        } else {
            return "用户名或者密码错误!";
        }
    }
}
